﻿
// CompactFlashWriterDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "CompactFlashWriter.h"
#include "CompactFlashWriterDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CCompactFlashWriterDlg 对话框



CCompactFlashWriterDlg::CCompactFlashWriterDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_COMPACTFLASHWRITER_DIALOG, pParent)
	, m_pszImageFilePath(_T(""))
	, m_nSectorPerTrack(0)
	, m_nTracks(0)
	, m_nTrackStart(0)
	, m_nSectorStart(0)
	, m_bMBR(FALSE)
	, m_szDiskSize(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CCompactFlashWriterDlg::OnOK()
{}

void CCompactFlashWriterDlg::OnCancel()
{}

void CCompactFlashWriterDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_COMBO_MEDIA, m_diskDriveList);
	DDX_Text(pDX, IDC_EDIT_IMAGE_PATH, m_pszImageFilePath);
	DDX_Text(pDX, IDC_EDIT_SECTOR_PER_TRACK, m_nSectorPerTrack);
	DDX_Control(pDX, IDC_COMBO_SECTOR_SIZE, m_ctrlComboSectorSize);
	DDX_Text(pDX, IDC_EDIT_TRACKS, m_nTracks);
	DDX_Text(pDX, IDC_EDIT_TRACK_START, m_nTrackStart);
	DDX_Text(pDX, IDC_EDIT_SECTOR_START, m_nSectorStart);
	DDX_Check(pDX, IDC_CHECK_MBR, m_bMBR);
	DDX_Text(pDX, IDC_STATIC_SIZE, m_szDiskSize);
}

void CCompactFlashWriterDlg::EnableUI(BOOL enabled)
{
	CWnd* p1 = (CWnd*)GetDlgItem(IDC_EDIT_TRACKS);
	CWnd* p2 = (CWnd*)GetDlgItem(IDC_EDIT_SECTOR_PER_TRACK);
	CWnd* p3 = (CWnd*)GetDlgItem(IDC_EDIT_TRACK_START);
	CWnd* p4 = (CWnd*)GetDlgItem(IDC_EDIT_SECTOR_START);
	CWnd* p5 = (CWnd*)GetDlgItem(IDC_COMBO_SECTOR_SIZE);

	p1->EnableWindow(enabled);
	p2->EnableWindow(enabled);
	p3->EnableWindow(enabled);
	p4->EnableWindow(enabled);
	p5->EnableWindow(enabled);
}

BEGIN_MESSAGE_MAP(CCompactFlashWriterDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_BUTTON_BROWSE, &CCompactFlashWriterDlg::OnBnClickedButtonBrowse)
	ON_BN_CLICKED(IDC_BUTTON_FLASH, &CCompactFlashWriterDlg::OnBnClickedButtonFlash)
	ON_BN_CLICKED(IDC_CHECK_MBR, &CCompactFlashWriterDlg::OnBnClickedCheckMbr)
	ON_CBN_SELCHANGE(IDC_COMBO_MEDIA, &CCompactFlashWriterDlg::OnCbnSelchangeComboMedia)
END_MESSAGE_MAP()


// CCompactFlashWriterDlg 消息处理程序

BOOL CCompactFlashWriterDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码

	// Enumerate removable disk drives
	m_diskManager.Enum();
	for(UINT i = 0; i < m_diskManager.GetCount(); i++) {
		DiskManager::DISK_DRIVE_INFO info;
		m_diskManager.GetInfo(&info, i);
		m_diskDriveList.AddString(info.szDriveNumber + " " + info.szDriveName);
		m_diskDriveList.SetItemDataPtr(i, (LPVOID)(LPCTSTR)info.szDriveFilePath);

		if(i == 0) {
			m_szDiskSize.Format(_T("Size: %dMB"), info.nTotalBytes / 1024 / 1024);
		}
	}
	if(m_diskDriveList.GetCount() == 0) {
		m_diskDriveList.AddString(_T("No Compact Flash Disk"));
		m_diskDriveList.SetItemDataPtr(0, (LPVOID)"");
	}
	m_diskDriveList.SetCurSel(0);

	// Init floppy settings
	m_bMBR = FALSE;
	m_nTracks = 77;
	m_nSectorPerTrack = 26;
	m_nTrackStart = 0;
	m_nSectorStart = 1;
	m_ctrlComboSectorSize.AddString(_T("128"));
	m_ctrlComboSectorSize.SetItemData(0, 128);

	m_ctrlComboSectorSize.AddString(_T("256"));
	m_ctrlComboSectorSize.SetItemData(1, 256);

	m_ctrlComboSectorSize.AddString(_T("512"));
	m_ctrlComboSectorSize.SetItemData(2, 512);
	m_ctrlComboSectorSize.SetCurSel(0);

	UpdateData(FALSE);
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CCompactFlashWriterDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CCompactFlashWriterDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CCompactFlashWriterDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CCompactFlashWriterDlg::OnClose()
{
	EndDialog(IDCANCEL);
}

void CCompactFlashWriterDlg::OnBnClickedButtonBrowse()
{
	// TODO: 在此添加控件通知处理程序代码
	CFileDialog fileDlg(TRUE, NULL, NULL, OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, _T("All Files (*.*)|*.*||"));

	if(fileDlg.DoModal() == IDOK) {
		CString filePath = fileDlg.GetPathName();
		m_pszImageFilePath = filePath;
	}
	else {
		m_pszImageFilePath = _T("");
	}
	UpdateData(FALSE);
}


void CCompactFlashWriterDlg::OnBnClickedButtonFlash()
{
	UpdateData(TRUE);

	int index = m_ctrlComboSectorSize.GetCurSel();
	UINT nSectorSize = m_ctrlComboSectorSize.GetItemData(index);
	FloppyDisk disk(m_nTracks, m_nSectorPerTrack, nSectorSize);
	
	if(!disk.Seek(m_nTrackStart, m_nSectorStart)) {
		CString msg;
		msg.Format(_T("Start track must be within: %d - %d\n Start sector must be within: %d - %d"),
			0, m_nTracks - 1, 1, m_nSectorPerTrack);
		AfxMessageBox(msg);
		return;
	}

	UINT nNumberOfTracksAffected = 0;
	UINT nNumberOfSectorsAffected = 0;
	UINT nNumberOfBytesWritten = 0;
	LPCTSTR pszDevicePath = (LPCTSTR)m_diskDriveList.GetItemDataPtr(m_diskDriveList.GetCurSel());

	// Init RAW disk.
	m_diskManager.InitDisk(pszDevicePath);

	BOOL bRet = FALSE;
	CString szError;
	CString szMsg;
	if(m_bMBR) {
		// Write image into MBR. 512B maximum
		if(disk.WriteMBR(pszDevicePath, m_pszImageFilePath, &nNumberOfBytesWritten, szError)) {
			szMsg.Format(_T("Flash MBR Complete!\n Bytes Written: %d"), nNumberOfBytesWritten);
		} else {
			szMsg.Format(_T("WriteMBR() -> %s"), (LPCTSTR)szError);
		}
	}
	else {
		// Write image into sectors. 1M maximum
		if(disk.WriteImage(pszDevicePath, m_pszImageFilePath,
			&nNumberOfTracksAffected, &nNumberOfSectorsAffected, &nNumberOfBytesWritten, szError)) {
			szMsg.Format(_T("Flash Complete!\n\nTracksAffected: %d\n SectorsAffected: %d\n BytesWritten: %d"),
				nNumberOfTracksAffected, nNumberOfSectorsAffected, nNumberOfBytesWritten);
		} else {
			szMsg.Format(_T("WriteImage() -> %s"), (LPCTSTR)szError);
		}
	}
	
	AfxMessageBox(szMsg);
}

void CCompactFlashWriterDlg::OnBnClickedCheckMbr()
{
	CButton* pCheckBox = (CButton*)GetDlgItem(IDC_CHECK_MBR);
	EnableUI(!pCheckBox->GetCheck());
}

void CCompactFlashWriterDlg::OnCbnSelchangeComboMedia()
{
	int index = m_diskDriveList.GetCurSel();
	for(UINT i = 0; i < m_diskManager.GetCount(); i++) {
		if(index == i) {
			DiskManager::DISK_DRIVE_INFO info;
			m_diskManager.GetInfo(&info, i);
			m_szDiskSize.Format(_T("Size: %dMB"), (UINT)info.nTotalBytes / 1024 / 1024);
			UpdateData(FALSE);
		}
	}
}
